package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.UserMapper;
import com.heima.admin.service.UserService;
import com.heima.model.admin.dtos.AdminLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, AdUser> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult login(AdminLoginDto adminLoginDto) {
        //查询传入的用户是否存在
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, adminLoginDto.getName());
        AdUser adUser = userMapper.selectOne(queryWrapper);
        if (adUser != null) {
            //存在用户
            String salt = adUser.getSalt();
            String password = adminLoginDto.getPassword();
            //拼接盐然后md5加密然后进行校验 password+salt
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (adUser.getPassword().equals(md5DigestAsHex)) {
                //密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //密码正确生成令牌返回
            //获取token
            String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            //敏感数据置空
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user", adUser);
            return ResponseResult.okResult(map);
        } else {
            //不存在用户
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户信息不存在");
        }
    }
}
